import { katexRender } from '~/utils/base.js'
import katexStyleContent from 'katex/dist/katex.min.css?inline' // 使用构建工具加载原始 CSS 内容

export default defineNuxtPlugin((nuxtApp) => {
  if (import.meta.client) {
    class WangEditorFormulaCard extends HTMLElement {
      span
      static get observedAttributes() {
        return ['data-value']
      }

      constructor() {
        super()
        const shadow = this.attachShadow({ mode: 'open' })
        const style = document.createElement('style')
        style.innerHTML = katexStyleContent
        shadow.appendChild(style)
        this.span = document.createElement('span')
        this.span.style.display = 'inline-block'
        shadow.appendChild(this.span)
      }

      attributeChangedCallback(name, oldValue, newValue) {
        if (name === 'data-value' && oldValue !== newValue) {
          katexRender(newValue || '', this.span)
        }
      }
    }

    if (!window.customElements.get('wcs-formula')) {
      window.customElements.define('wcs-formula', WangEditorFormulaCard)
    }
  }
})
